<template>
  <div>
    <div class="topBtn">
      <div class="sizeBig">
        <span>生产领料</span>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="add" style="height:37px">新增领料单</el-button>
        <el-button type="primary" @click="remove">
          <i class="icon-remove"></i>删除
        </el-button>
        <el-button type="primary" @click="edit">
          <i class="icon-edit"></i>修改
        </el-button>
        <el-button type="primary" icon="el-icon-search" @click="Detailed" style="height:37px">查询</el-button>
        <el-button type="primary" @click="check">
          <i class="icon-check"></i>审核
        </el-button>
        <el-button type="primary" @click="exportExcel">
          <i class="icon-export"></i>导出
        </el-button>
        <el-button type="primary">
          <i class="icon-printing"></i>打印
        </el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">
        生产计划员生成生产计划后，该生产计划会按BOM的物料转换关系生成需要的物料清单，产线按照该物料需求清单找仓库申请领料即可。注意物料抛料率的损耗计算，手动领料时解决生成计划之外的物料损耗和使用情况，可以手动添加物料来领用。
        <span
          class="skip"
        >查看帮助文档</span>
      </p>
    </div>
    <div class="inputcontent">
      <el-input v-model="search" placeholder="请输入内容" class="inSearch"></el-input>
      <div class="iconSearch"></div>
    </div>
    <div class="table">
      <Table :reset="reset" v-on:getId="getListId" id="out-table" v-on:changeData="changedata"></Table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <!-- <el-button type="primary" class="detai" @click="Detailed">查看领料明细</el-button> -->
      <el-pagination
        @current-change="handleCurrentChange"
        :page-sizes="[5]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="TotalNum"
      ></el-pagination>
    </div>
    <div class="table1">
      <Table1 :detailed="detailed"></Table1>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange1"
        :page-sizes="[3]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="TotalNum1"
      ></el-pagination>
    </div>

    <!-- 新增领料单弹出框 -->
    <el-dialog title="新增领料单" center :visible.sync="addDialogVisible" width="800px">
      <Table2 :addData="addData" ref="addReq"></Table2>
      <span class="skip" @click="add3">添加</span>
      <div style="marginLeft:200px;">
        <el-button @click="addDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="preser">保存</el-button>
      </div>
    </el-dialog>

    <!-- 修改领料单弹出框 -->
    <el-dialog title="修改领料单" center :visible.sync="editDialogVisible" width="800px">
      <Table3 :editData="editData" :editForm="editForm" ref="avatar1"></Table3>
      <div style="marginLeft:300px;">
        <el-button @click="editDialogVisible=false">取消</el-button>
        <el-button style="marginLeft:30px;" type="primary" @click="modify">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMaterialRequisitionDOList, //查询领料单列表
  getMaterialRequisitionDetailDOList, //查询领料单明细
  insertRequisition, //新增领料单
  updateRequisitionStatus, // 删除或审核
  updateRequisition, // 修改
  getMaterialItemList //物料列表查询
} from "@/api/picking";
import Table from "./components/pickingTable";
import Table1 from "./components/pickingTable1";
import Table2 from "./components/pickingAddRequisition";
import Table3 from "./components/pickingEditRequisition";
import { delay } from "@/utils/autoSearch";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { Promise } from "q";
import { parse } from "path";

export default {
  name: "picking",
  components: {
    Table,
    Table1,
    Table2,
    Table3
  },
  data() {
    return {
      search: "",
      currentPage:1,
      TotalNum: 0, //总条数
      TotalNum1: 0,
      reset: [], //领料单表
      detailed: [], //物料明细表
      addlist: [],
      addDialogVisible: false, // 新增领料单弹框
      editDialogVisible: false, //修改领料单弹出框
      jsonData:{},
      arr: [],
      lists:[],
      addData: [
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        }
      ],
      editData: [],
      editForm: {
        OrderBagId: "",
        WorkstationId: ""
      }
    };
  },
  watch: {
    //用来监听页面变量的改变
    //监听搜索，300ms执行一次fetchData方法（去搜索）
    search() {
      delay(() => {
        this.fetchData();
      }, 300);
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 自动搜索的方法
    async fetchData(val) {
      this.init({ keyName: this.search });
    },
    // 分页
    handleCurrentChange(val) {
      getMaterialRequisitionDOList({
        keyName: this.search,
        status: -1,
        page: val,
        pageSize: 5
      }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
        }
      });
    },
    // 请求数据
    init() {
      this.reset = [];
      getMaterialRequisitionDOList({
        keyName: this.search,
        status: -1,
        page: 1,
        pageSize: 5
      }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
          this.TotalNum = res.Result.TotalNum;
        }
      });
    },

    getListId(listId) {
      this.checkIds = listId;
    },
    changedata(data) {
      this.addlist = data;
      console.log(this.addlist);
    },

    //查询领料明细
    Detailed() {
      if (this.addlist.length !== 1) {
        this.$message("请勾选一项");
      } else {
        getMaterialRequisitionDetailDOList({
          requisitionID: this.addlist[0].RequisitionID,
          page: 1,
          pageSize: 3
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.$message({
              type: "success",
              message: "查询成功"
            });
            this.detailed = res.Result.Items;
            this.TotalNum1 = res.Result.TotalNum;
          }
        });
      }
    },
    handleCurrentChange1(val) {
      this.currentPage = val
      getMaterialRequisitionDetailDOList({
        requisitionID: this.addlist[0].RequisitionID,
        page: this.currentPage,
        pageSize: 3
      }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.detailed = res.Result.Items;
        }
      });
    },
    add3(){
      this.addData.push(
        {
          materialCode: "",
          materialItemID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          materialName: "",
          quantity: ""
        }
      )
    },
    // 新增领料单
    add() {
      this.addDialogVisible = true;
      this.addData = [
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        },
        {
          materialCode: "",
          materialItemID: "",
          RequisitionDetailID: "",
          materialName: "",
          quantity: ""
        }
      ];
      getMaterialItemList({ keyName: "" }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.materialList = res.Result;
          this.materialList.forEach(el => {
            this.addData[0].materialItemID = el.MaterialItemID;
          });
        }
        this.$refs.addReq.WorkstationId = "";
        this.$refs.addReq.OrderBagId = "";
      });  
    },
    preser() {
      let itemlist = [];
      this.jsonData = {}
      this.addData.forEach(el => {
        itemlist += el.quantity + "";
      });
      itemlist = itemlist.substr(0, itemlist.length);

      for (var i = 0; i < itemlist.length; i++) {
        var list = {
          MaterialItemID: this.addData[0].materialItemID,
          Quantity: itemlist[i]
        };
        this.arr.push(list);
      }
      console.log(this.arr);
      this.jsonData = {
        OrderBagId: parseInt(this.$refs.addReq.OrderBagId),
        WorkstationId: this.$refs.addReq.WorkstationId,
        MaterialRequisitionDetails: this.arr
      };
      insertRequisition({ jsonString: JSON.stringify(this.jsonData) }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.$message({
            type: "success",
            message: "新增成功"
          });
          this.addDialogVisible = false;
        }
        this.init();
        this.$refs.addReq.WorkstationId = "";
        this.$refs.addReq.OrderBagId = "";
      });
    },
    // 删除
    remove() {
      if (this.addlist.length !== 1) {
        this.$message("请勾选一项");
      } else {
        updateRequisitionStatus({
          requisitionID: this.addlist[0].RequisitionID,
          status: 3
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.$message({
              type: "success",
              message: "删除成功"
            });
          }
          this.init();
        });
      }
    },
    // 修改
    edit() {
      if (this.addlist.length !== 1) {
        this.$message("请勾选一项");
      } else {
        this.editDialogVisible = true;
        
        getMaterialRequisitionDetailDOList({
          requisitionID: this.addlist[0].RequisitionID,
          page: this.currentPage,
          pageSize: 1000
        })
          .then(res => {
            if (parseInt(res.Code) === 1) {
              // this.detailed = res.Result.Items;
              this.TotalNum1 = res.Result.TotalNum;
              this.editData = res.Result.Items;
            }
            return getMaterialItemList({ keyName: "" });
          })
          .then(res => {
            if (parseInt(res.Code) === 1) {
              this.materialList = res.Result;
              this.materialList.forEach(el => {
                this.addData[0].materialItemID = el.MaterialItemID;
              });
            //   console.log(this.addData[0].materialItemID);
            }
          })
          .catch(err => void console.log(err));
        this.editForm.OrderBagId = this.addlist[0].OrderBagId;
        this.editForm.WorkstationId = this.addlist[0].WorkstationId;
      }
    },
    modify() {
      this.lists = []
      this.jsonData = {}
      for(let i = 0; i < this.editData.length; i++){
        let list = {
          RequisitionDetailID: this.editData[i].RequisitionDetailID,
          MaterialItemID: this.editData[i].MaterialItemID,
          Quantity: parseInt(this.editData[i].Quantity)
        }
        this.lists.push(list)
      }
      
      this.jsonData = {
        RequisitionID: this.editData[0].RequisitionID,
        OrderBagId: parseInt(this.editForm.OrderBagId),
        WorkstationId: this.editForm.WorkstationId,
        MaterialRequisitionDetails: this.lists
      };
      console.log(this.jsonData)

      updateRequisition({ jsonString: JSON.stringify(this.jsonData) }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.$message({
            type: "success",
            message: "修改成功"
          });
        }
        this.init();
        this.editDialogVisible = false;
      });
    },
    // 审核
    check() {
      if (this.addlist.length !== 1) {
        this.$message("请勾选一项");
      } else {
        updateRequisitionStatus({
          requisitionID: this.addlist[0].RequisitionID,
          status: 1
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.$message({
              type: "success",
              message: "审核成功"
            });
          }
          this.init();
        });
      }
    },
    // 导出
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#out-table"),
        xlsxParam
      );

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "生产领料表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    }
    // 打印
  }
};
</script>

<style scoped lang="scss">
.sizeBig {
  font-size: 16px;
}
.topBtn {
  height: 60px;
  width: 98%;
  margin: 0 auto;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  .icon-remove {
    display: inline-block;
    width: 14px;
    height: 14px;
    margin: 0 3px 0 0;
    background: url("image/shanchu.png") no-repeat;
    vertical-align: middle;
  }
  .icon-edit {
    display: inline-block;
    width: 14px;
    height: 14px;
    margin: 0 3px 0 0;
    background: url("image/xiugai.png") no-repeat;
    vertical-align: middle;
  }
  .icon-check {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin: 0 3px 2px 0;
    background: url("image/shenhe.png") no-repeat;
    vertical-align: middle;
  }
  .icon-export {
    display: inline-block;
    width: 13px;
    height: 12px;
    margin: 0 3px 2px 0;
    background: url("image/daochu.png") no-repeat;
    vertical-align: middle;
  }
  .icon-printing {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin: 0 3px 2px 0;
    background: url("image/dayin.png") no-repeat;
    vertical-align: middle;
  }
}
.message {
  width: 98%;
  margin: 0 auto;
  height: 80px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(238, 238, 238, 1);
  font-size: 14px;
  .character {
    margin: 20px 20px 21px 20px;
    line-height: 25px;
    color: #999999;
    .skip {
      color: #0095ff;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
.inputcontent {
  width: 98%;
  margin: 0 auto;
  height: 80px;
  position: relative;
  padding-top: 21px;
  box-sizing: border-box;
  .iconSearch {
    position: absolute;
    left: 277px;
    top: 30px;
    width: 20px;
    height: 20px;
    background-image: url("./image/搜索.png");
    background-repeat: no-repeat;
    cursor: pointer;
  }
  .inSearch {
    width: 308px;
    height: 40px;
  }
}
.table {
  width: 98%;
  margin: 0 auto;
}
.block {
  text-align: right;
  margin: 20px 20px 10px 0;
  .detai {
    float: left;
    margin-left: 10px;
  }
}
.table1 {
  width: 98%;
  margin: 0 auto;
}
.block1 {
  text-align: right;
  margin: 28px 20px 0 0;
}
.skip{  
        float: left;          
        color: #0095FF;
        cursor:pointer;        
    }   
</style>
